'use client';

import React, { useState, useEffect } from 'react';
import {
  PageHeader,
  Card,
  Button,
  InputGroup,
} from '@/components/common';

import { ZHAIQUAN_SIDECHAIN_URL, ZHAIQUAN_MAINCHAIN_URL } from '@/utils/config';

const MAINCHAIN_API_URL = ZHAIQUAN_MAINCHAIN_URL;
const SIDECHAIN_API_URL = ZHAIQUAN_SIDECHAIN_URL;

// 类型定义
interface MintRequest {
  amount: number;
  tokenID: string;
  clientID: string;
}

interface HTLSenderRequest {
  clientID: string;
  seed: number;
  timeout: number;
  amount: number;
  tokenID: string;
}

interface HTLReceiverRequest {
  hashValue: string;
  clientID: string;
  timeout: number;
  amount: number;
  tokenID: string;
}

interface UnlockRequest {
  htlKey: string;
  preimage: string;
}

interface BalanceData {
  clientID: string;
  tokenID: string;
  balance: number;
}



export default function CrossChainTransferPage() {
  const [mainchainRunning, setMainchainRunning] = useState<boolean | null>(null);
  const [sidechainRunning, setSidechainRunning] = useState<boolean | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [logs, setLogs] = useState<string[]>([]);
  
  // 流程数据状态
  const [mintData, setMintData] = useState<MintRequest>({
    amount: 1000000000,
    tokenID: 'tokenABC',
    clientID: 'user1'
  });

  const [htlSenderData, setHTLSenderData] = useState<HTLSenderRequest>({
    clientID: 'user1',
    seed: 987654321,
    timeout: 300,
    amount: 5,
    tokenID: 'tokenABC'
  });

  const [htlReceiverData, setHTLReceiverData] = useState<HTLReceiverRequest>({
    hashValue: '',
    clientID: 'user1',
    timeout: 300,
    amount: 5,
    tokenID: 'tokenABC'
  });

  const [unlockData, setUnlockData] = useState<UnlockRequest>({
    htlKey: '',
    preimage: '987654321'
  });

  const [mainchainBalances, setMainchainBalances] = useState<BalanceData[]>([]);
  const [sidechainBalances, setSidechainBalances] = useState<BalanceData[]>([]);
  const [htlKey, setHtlKey] = useState('');
  const [receiverHtlKey, setReceiverHtlKey] = useState('');

  // 添加日志
  const addLog = (message: string) => {
    setLogs(prev => [...prev, `${new Date().toLocaleTimeString()}: ${message}`]);
  };

  // 检查服务器状态
  const checkServers = async () => {
    try {
      await fetch(`${MAINCHAIN_API_URL}/assert/balance?chainId=chain1`);
      setMainchainRunning(true);
    } catch (error) {
      console.error('主链连接失败:', error);
      setMainchainRunning(false);
    }

    try {
      await fetch(`${SIDECHAIN_API_URL}/assert/balance?chainId=chain1`);
      setSidechainRunning(true);
    } catch (error) {
      console.error('侧链连接失败:', error);
      setSidechainRunning(false);
    }
  };

  // 获取余额
  const loadBalances = async () => {
    try {
      const mainResponse = await fetch(`${MAINCHAIN_API_URL}/assert/balance?chainId=chain1`);
      if (mainResponse.ok) {
        const result = await mainResponse.json();
        setMainchainBalances(result.data || []);
      }
    } catch (error) {
      console.error('获取主链余额失败:', error);
    }

    try {
      const sideResponse = await fetch(`${SIDECHAIN_API_URL}/assert/balance?chainId=chain1`);
      if (sideResponse.ok) {
        const result = await sideResponse.json();
        setSidechainBalances(result.data || []);
      }
    } catch (error) {
      console.error('获取侧链余额失败:', error);
    }
  };

  useEffect(() => {
    checkServers();
    loadBalances();
  }, []);

  // 步骤1：铸造主链代币
  const handleMintMainchain = async () => {
    setIsProcessing(true);
    addLog('开始铸造主链代币...');
    try {
      const response = await fetch(`${MAINCHAIN_API_URL}/assert/mint?chainId=chain1`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(mintData),
      });

      if (response.ok) {
        const result = await response.json();
        if (result.success) {
          addLog(`主链代币铸造成功！数量: ${mintData.amount}`);
          setCurrentStep(1);
          await loadBalances();
        } else {
          addLog('主链代币铸造失败');
        }
      } else {
        addLog('主链代币铸造请求失败');
      }
    } catch (error) {
      console.error('主链代币铸造失败:', error);
      addLog('主链代币铸造失败，请检查网络连接');
    } finally {
      setIsProcessing(false);
    }
  };

  // 步骤2：铸造侧链代币
  const handleMintSidechain = async () => {
    setIsProcessing(true);
    addLog('开始铸造侧链代币...');
    try {
      const response = await fetch(`${SIDECHAIN_API_URL}/assert/mint?chainId=chain1`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(mintData),
      });

      if (response.ok) {
        const result = await response.json();
        if (result.success) {
          addLog(`侧链代币铸造成功！数量: ${mintData.amount}`);
          setCurrentStep(2);
          await loadBalances();
        } else {
          addLog('侧链代币铸造失败');
        }
      } else {
        addLog('侧链代币铸造请求失败');
      }
    } catch (error) {
      console.error('侧链代币铸造失败:', error);
      addLog('侧链代币铸造失败，请检查网络连接');
    } finally {
      setIsProcessing(false);
    }
  };

  // 步骤3：创建发送方HTL
  const handleCreateSenderHTL = async () => {
    setIsProcessing(true);
    addLog('创建发送方HTL...');
    try {
      const response = await fetch(`${MAINCHAIN_API_URL}/assert/htl/sender?chainId=chain1`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(htlSenderData),
      });

      if (response.ok) {
        const result = await response.json();
        if (result.success && result.htlKey) {
          setHtlKey(result.htlKey);
          setHTLReceiverData(prev => ({ ...prev, hashValue: result.htlKey }));
          addLog(`发送方HTL创建成功！HTL Key: ${result.htlKey}`);
          setCurrentStep(3);
          await loadBalances();
        } else {
          addLog('发送方HTL创建失败');
        }
      } else {
        addLog('发送方HTL创建请求失败');
      }
    } catch (error) {
      console.error('发送方HTL创建失败:', error);
      addLog('发送方HTL创建失败，请检查网络连接');
    } finally {
      setIsProcessing(false);
    }
  };

  // 步骤4：创建接收方HTL
  const handleCreateReceiverHTL = async () => {
    setIsProcessing(true);
    addLog('创建接收方HTL...');
    try {
      const response = await fetch(`${SIDECHAIN_API_URL}/assert/htl/receiver?chainId=chain1`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(htlReceiverData),
      });

      if (response.ok) {
        const result = await response.json();
        if (result.success && result.htlKey) {
          setReceiverHtlKey(result.htlKey);
          setUnlockData(prev => ({ ...prev, htlKey: result.htlKey }));
          addLog(`接收方HTL创建成功！HTL Key: ${result.htlKey}`);
          setCurrentStep(4);
          await loadBalances();
        } else {
          addLog('接收方HTL创建失败');
        }
      } else {
        addLog('接收方HTL创建请求失败');
      }
    } catch (error) {
      console.error('接收方HTL创建失败:', error);
      addLog('接收方HTL创建失败，请检查网络连接');
    } finally {
      setIsProcessing(false);
    }
  };

  // 步骤5：解锁接收方HTL
  const handleUnlockReceiverHTL = async () => {
    setIsProcessing(true);
    addLog('解锁接收方HTL...');
    try {
      const response = await fetch(`${SIDECHAIN_API_URL}/assert/unlock/receiver/htl_key123?chainId=chain1`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(unlockData),
      });

      if (response.ok) {
        const result = await response.json();
        if (result.success) {
          addLog('接收方HTL解锁成功！跨链转账完成');
          setCurrentStep(5);
          await loadBalances();
        } else {
          addLog('接收方HTL解锁失败');
        }
      } else {
        addLog('接收方HTL解锁请求失败');
      }
    } catch (error) {
      console.error('接收方HTL解锁失败:', error);
      addLog('接收方HTL解锁失败，请检查网络连接');
    } finally {
      setIsProcessing(false);
    }
  };

  const steps = [
    { title: '铸造主链代币', description: '在主链上铸造初始代币', completed: currentStep > 0 },
    { title: '铸造侧链代币', description: '在侧链上铸造初始代币', completed: currentStep > 1 },
    { title: '创建发送方HTL', description: '在主链创建哈希时间锁', completed: currentStep > 2 },
    { title: '创建接收方HTL', description: '在侧链创建对应的HTL', completed: currentStep > 3 },
    { title: '解锁接收方HTL', description: '提供原像解锁完成转账', completed: currentStep > 4 },
  ];

  return (
    <div className="min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
      <PageHeader title="跨链代币转移演示 (HTL)" />

      <main className="flex flex-col gap-8 items-center w-full max-w-6xl mx-auto pt-20">
        
        {/* 服务器状态 */}
        <div className="w-full bg-gray-50 rounded-lg p-6">
          <h2 className="text-xl font-semibold mb-4">跨链系统状态</h2>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
              <span className="font-medium">主链状态: </span>
              <span className={`font-semibold ${mainchainRunning ? 'text-green-600' : 'text-red-600'}`}>
                {mainchainRunning ? '运行中' : '离线'}
              </span>
            </div>
            <div>
              <span className="font-medium">侧链状态: </span>
              <span className={`font-semibold ${sidechainRunning ? 'text-green-600' : 'text-red-600'}`}>
                {sidechainRunning ? '运行中' : '离线'}
              </span>
            </div>
            <div>
              <span className="font-medium">当前步骤: </span>
              <span className="text-blue-600 font-semibold">{currentStep}/5</span>
            </div>
            <Button onClick={checkServers} variant="secondary" className="text-sm">
              重新检查
            </Button>
          </div>
        </div>

        {/* 流程步骤显示 */}
        <div className="w-full bg-blue-50 rounded-lg p-6">
          <h3 className="text-lg font-semibold mb-4">跨链转移流程</h3>
          <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
            {steps.map((step, index) => (
              <div key={index} className="text-center">
                <div className={`w-8 h-8 rounded-full flex items-center justify-center mx-auto mb-2 font-semibold ${
                  step.completed ? 'bg-green-500 text-white' : 
                  currentStep === index ? 'bg-blue-500 text-white' : 
                  'bg-gray-300 text-gray-600'
                }`}>
                  {index + 1}
                </div>
                <p className="text-sm font-medium">{step.title}</p>
                <p className="text-xs text-gray-600">{step.description}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 w-full">
          {/* 左侧：操作面板 */}
          <div className="space-y-6">
            {/* 铸造代币配置 */}
            <Card title="代币铸造配置">
              <div className="space-y-4">
                <InputGroup
                  label="代币ID"
                  value={mintData.tokenID}
                  onChange={(value) => setMintData({...mintData, tokenID: value})}
                  type="text"
                />
                <InputGroup
                  label="用户ID"
                  value={mintData.clientID}
                  onChange={(value) => setMintData({...mintData, clientID: value})}
                  type="text"
                />
                <InputGroup
                  label="铸造数量"
                  value={mintData.amount.toString()}
                  onChange={(value) => setMintData({...mintData, amount: parseInt(value) || 0})}
                  type="number"
                />
                
                <div className="grid grid-cols-2 gap-2">
                  <Button 
                    onClick={handleMintMainchain}
                    disabled={!mainchainRunning || isProcessing}
                    variant="primary"
                  >
                    {isProcessing && currentStep === 0 ? '铸造中...' : '铸造主链代币'}
                  </Button>
                  <Button 
                    onClick={handleMintSidechain}
                    disabled={!sidechainRunning || isProcessing || currentStep < 1}
                    variant="primary"
                  >
                    {isProcessing && currentStep === 1 ? '铸造中...' : '铸造侧链代币'}
                  </Button>
                </div>
              </div>
            </Card>

            {/* HTL配置 */}
            <Card title="HTL转账配置">
              <div className="space-y-4">
                <InputGroup
                  label="种子值"
                  value={htlSenderData.seed.toString()}
                  onChange={(value) => setHTLSenderData({...htlSenderData, seed: parseInt(value) || 0})}
                  type="number"
                />
                <InputGroup
                  label="超时时间(秒)"
                  value={htlSenderData.timeout.toString()}
                  onChange={(value) => setHTLSenderData({...htlSenderData, timeout: parseInt(value) || 300})}
                  type="number"
                />
                <InputGroup
                  label="转账数量"
                  value={htlSenderData.amount.toString()}
                  onChange={(value) => setHTLSenderData({...htlSenderData, amount: parseInt(value) || 0})}
                  type="number"
                />
                
                <Button 
                  onClick={handleCreateSenderHTL}
                  disabled={!mainchainRunning || isProcessing || currentStep < 2}
                  variant="success"
                  className="w-full"
                >
                  {isProcessing && currentStep === 2 ? '创建中...' : '创建发送方HTL'}
                </Button>
              </div>
            </Card>
          </div>

          {/* 右侧：状态和操作 */}
          <div className="space-y-6">
            {/* HTL状态 */}
            <Card title="HTL状态">
              <div className="space-y-4">
                <div className="bg-gray-50 p-3 rounded">
                  <p className="text-sm text-gray-600 mb-1">发送方HTL Key:</p>
                  <p className="font-mono text-xs break-all">{htlKey || '未生成'}</p>
                </div>
                <div className="bg-gray-50 p-3 rounded">
                  <p className="text-sm text-gray-600 mb-1">接收方HTL Key:</p>
                  <p className="font-mono text-xs break-all">{receiverHtlKey || '未生成'}</p>
                </div>
                
                <Button 
                  onClick={handleCreateReceiverHTL}
                  disabled={!sidechainRunning || isProcessing || currentStep < 3 || !htlKey}
                  variant="success"
                  className="w-full"
                >
                  {isProcessing && currentStep === 3 ? '创建中...' : '创建接收方HTL'}
                </Button>
              </div>
            </Card>

            {/* 解锁操作 */}
            <Card title="解锁HTL">
              <div className="space-y-4">
                <InputGroup
                  label="原像值"
                  value={unlockData.preimage}
                  onChange={(value) => setUnlockData({...unlockData, preimage: value})}
                  type="text"
                />
                <div className="bg-gray-50 p-3 rounded">
                  <p className="text-sm text-gray-600 mb-1">HTL Key:</p>
                  <p className="font-mono text-xs break-all">{unlockData.htlKey || '等待生成'}</p>
                </div>
                
                <Button 
                  onClick={handleUnlockReceiverHTL}
                  disabled={!sidechainRunning || isProcessing || currentStep < 4 || !unlockData.htlKey}
                  variant="success"
                  className="w-full"
                >
                  {isProcessing && currentStep === 4 ? '解锁中...' : '解锁接收方HTL'}
                </Button>
              </div>
            </Card>

            {/* 余额显示 */}
            <Card title="代币余额">
              <div className="space-y-4">
                <div>
                  <h4 className="font-medium mb-2">主链余额</h4>
                  {mainchainBalances.length === 0 ? (
                    <p className="text-gray-500 text-sm">暂无余额数据</p>
                  ) : (
                    mainchainBalances.map((balance, index) => (
                      <div key={index} className="bg-blue-50 p-2 rounded text-sm">
                        <p>{balance.clientID} - {balance.tokenID}: {balance.balance.toLocaleString()}</p>
                      </div>
                    ))
                  )}
                </div>
                
                <div>
                  <h4 className="font-medium mb-2">侧链余额</h4>
                  {sidechainBalances.length === 0 ? (
                    <p className="text-gray-500 text-sm">暂无余额数据</p>
                  ) : (
                    sidechainBalances.map((balance, index) => (
                      <div key={index} className="bg-green-50 p-2 rounded text-sm">
                        <p>{balance.clientID} - {balance.tokenID}: {balance.balance.toLocaleString()}</p>
                      </div>
                    ))
                  )}
                </div>
                
                <Button onClick={loadBalances} variant="secondary" className="w-full text-sm">
                  刷新余额
                </Button>
              </div>
            </Card>
          </div>
        </div>

        {/* 操作日志 */}
        <Card title={`操作日志 (${logs.length}条)`} className="w-full">
          <div className="max-h-60 overflow-y-auto space-y-1">
            {logs.length === 0 ? (
              <p className="text-gray-500 text-center py-4">暂无操作记录</p>
            ) : (
              logs.map((log, index) => (
                <div key={index} className="text-sm font-mono bg-gray-50 p-2 rounded">
                  {log}
                </div>
              ))
            )}
          </div>
          <div className="mt-4 pt-4 border-t">
            <Button 
              onClick={() => setLogs([])} 
              variant="secondary" 
              className="text-sm"
            >
              清空日志
            </Button>
          </div>
        </Card>
      </main>
    </div>
  );
}
